#include <iostream>
#include <string>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "Log.hpp"

using namespace log_ns;

enum
{
    SOCKET_ERROR = 1,
    BIND_ERROR
};

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        std::cerr << "usage: " << argv[0] << " serverIP serverPORT" << std::endl;
        exit(0);
    }

    std::string serverip = argv[1];
    int serverport = std::stoi(argv[2]);
    int sockfd = ::socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        LOG(FATAL, "sockfd error\n");
        exit(SOCKET_ERROR);
    }
    LOG(DEBUG, "sockfd create sucess, sockfd: %d\n", sockfd);

    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    ::inet_pton(AF_INET, serverip.c_str(), &server.sin_addr);

    if (::connect(sockfd, (sockaddr *)&server, sizeof(server)) < 0)
    {
        std::cerr << "connect socket error" << std::endl;
        exit(2);
    }

    while (true)
    {
        std::string line;
        std::cout << "Please enter# ";
        std::getline(std::cin, line);

        ::write(sockfd, line.c_str(), line.size());

        char inbuffer[1024];
        int n = read(sockfd, inbuffer, sizeof(inbuffer) - 1);
        if (n > 0)
        {
            inbuffer[n] = 0;
            std::cout << inbuffer << std::endl;
        }
        else
            break;
    }

    ::close(sockfd);
    return 0;
}